package com.suyl.easypoi.easypoidemo.excelInport.handler;

import cn.afterturn.easypoi.handler.inter.IExcelDictHandler;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class UserDictExcelHandler implements IExcelDictHandler {

    private static final Logger LOG = LoggerFactory.getLogger(UserDictExcelHandler.class);

    @Override
    public String toName(String s, Object o, String s1, Object o1) {
        return getDictCache(s).get(s1);
    }

    @Override
    public String toValue(String s, Object o, String s1, Object o1) {
        return getDictCache(s).inverse().get(o1);
    }

    public BiMap<String, String> getDictCache(String catalog) {
        BiMap<String, String> weekNameMap = HashBiMap.create();
        if (catalog.equals("ify")) {
            weekNameMap.put("1", "是");
            weekNameMap.put("2", "否");
        } else if (catalog.equals("bDict")) {
            weekNameMap.put("01B", "代码01B");
            weekNameMap.put("02B", "代码02B");
        }
        return weekNameMap;
    }


    //定义一个本地缓存临时缓存字典数据
    ListeningExecutorService refreshPools = MoreExecutors
            .listeningDecorator(Executors.newFixedThreadPool(2));
    LoadingCache<String, Map<String, String>> cache = CacheBuilder.newBuilder()
            .refreshAfterWrite(30, TimeUnit.MINUTES).expireAfterAccess(1, TimeUnit.HOURS).maximumSize(50)
            .build(new CacheLoader<String, Map<String, String>>() {
                @Override
                // 当本地缓存命没有中时，调用load方法获取结果并将结果缓存
                public Map<String, String> load(String key) {
                    LOG.info("开始从远程读取缓存到本地");
                    Map<String, String> data = getDictCache(key);
                    return data;
                }

                // 刷新
                @Override
                public ListenableFuture<Map<String, String>> reload(String key, Map<String, String> oldValue)
                        throws Exception {
                    LOG.info("刷新远程读取缓存到本地");
                    return refreshPools.submit(new Callable<Map<String, String>>() {
                        @Override
                        public Map<String, String> call() throws Exception {
                            LOG.info("开始从远程读取缓存到本地");
                            Map<String, String> data = getDictCache(key);
                            return data;
                        }
                    });
                }
            });
}
